package com.xx.questionnaire.isms.DorEModule.arithmetic;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

/**
 * SHA(Secure Hash Algorithm，安全散列算法)<br>
 * 
 * @author 王志华
 * @特点
 * 分组长度：512byte<br>
 * 摘要长度：160byte<br>
 * for 次数：80<br>
 * 报文最大长度：有限
 *
 */
 

public final class SHA {
	static Logger log = Logger.getLogger(SHA.class);
	//只能隐式默认为128
	static final String SHA_DEFAULT="SHA";
	static final String SHA_256="SHA-256";
	static final String SHA_384="SHA-384";
	static final String SHA_512="SHA-512";
	public static String SHAEncode(String str){
		return SHAEncode(str, SHA_DEFAULT);
	}
	 public static String SHAEncode(String str,String EncodeLeng){
		 if(str.equals("")){
			 return null;
		 }else if(EncodeLeng ==null){
			 EncodeLeng = SHA_DEFAULT;
		 }
		 
		 MessageDigest md = null;
		  
		 byte[] by;
		 try {
			md = MessageDigest.getInstance(EncodeLeng);
			byte[] byteArray = str.getBytes("UTF-8");
			md.update(byteArray);
			by = md.digest();
			log.info("摘要长度："+by.length);
			StringBuffer buffer = new StringBuffer();
			for(int i=0;i<by.length;i++){
				int val = (int)by[i] & 0xff;
				if(val < 16){
					buffer.append("0");
				}
				buffer.append(Integer.toHexString(val));
			}
			log.info("SHA算法的16进制密文长度为："+buffer.toString().length());
			return buffer.toString();
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return null;
		 
	 }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String a ="amigoxiexiexingxing";
		String key = SHA.SHAEncode(a,null);
		System.out.println(key+","+key.length());
		 

	}

}
